package com.gzz.orchid.context.application.rbac.convert;

import com.gzz.orchid.common.core.tuple.TreeNode;
import com.gzz.orchid.context.application.rbac.pojo.ModuleDto;
import com.gzz.orchid.context.application.rbac.pojo.OrganizationDto;
import com.gzz.orchid.context.infrastructure.persistence.entity.sys.SysModulePo;
import com.gzz.orchid.context.infrastructure.persistence.entity.sys.SysOrganizationPo;

import java.util.Comparator;
import java.util.List;

/**
 * 目录树转换
 *
 * @author higmd
 */
public class RbacAssembler {
    /**
     * 模块树选项
     */
    public static List<TreeNode<Long>> mapModuleTreeOptions(List<SysModulePo> source, Long parentId) {
        return source.stream()
                .filter(item -> item.getParentId().equals(parentId))
                .sorted(Comparator.comparing(SysModulePo::getIdx, Comparator.reverseOrder()))
                .map(item -> {
                    var node = TreeNode.of(item.getName(), item.getId());
                    node.setChildren(RbacAssembler.mapModuleTreeOptions(source, item.getId()));
                    return node;
                })
                .toList();
    }

    /**
     * 模块树选项
     */
    public static List<ModuleDto> mapModuleTreeDto(List<SysModulePo> source, Long parentId) {
        return source.stream()
                .filter(item -> item.getParentId().equals(parentId))
                .sorted(Comparator.comparing(SysModulePo::getIdx, Comparator.reverseOrder()))
                .map(po -> {
                    var dto = ModuleConverter.INSTANCE.mapDto(po);
                    dto.setChildren(RbacAssembler.mapModuleTreeDto(source, po.getId()));
                    return dto;
                })
                .toList();
    }

    /**
     * 机构组织树选项
     */
    public static List<TreeNode<Long>> mapOrganizationTreeOptions(List<SysOrganizationPo> source, Long parentId) {
        return source.stream()
                .filter(item -> item.getParentId().equals(parentId))
                .sorted(Comparator.comparing(SysOrganizationPo::getIdx, Comparator.reverseOrder()))
                .map(item -> {
                    var node = TreeNode.of(item.getName(), item.getId());
                    node.setChildren(RbacAssembler.mapOrganizationTreeOptions(source, item.getId()));
                    return node;
                })
                .toList();
    }

    /**
     * 机构组织树选项
     */
    public static List<OrganizationDto> mapOrganizationTreeDto(List<SysOrganizationPo> source, Long parentId) {
        return source.stream()
                .filter(item -> item.getParentId().equals(parentId))
                .sorted(Comparator.comparing(SysOrganizationPo::getIdx, Comparator.reverseOrder()))
                .map(po -> {
                    var dto = OrganizationConverter.INSTANCE.mapDto(po);
                    dto.setChildren(RbacAssembler.mapOrganizationTreeDto(source, po.getId()));
                    return dto;
                })
                .toList();
    }
}
